package com.yupi.picturebackend.manager.websocket;

import cn.hutool.core.util.StrUtil;
import com.yupi.picturebackend.manager.auth.SpaceUserAuthManager;
import com.yupi.picturebackend.manager.auth.model.SpaceUserPermissionConstant;
import com.yupi.picturebackend.model.entity.Picture;
import com.yupi.picturebackend.model.entity.Space;
import com.yupi.picturebackend.model.entity.User;
import com.yupi.picturebackend.model.enums.SpaceTypeEnum;
import com.yupi.picturebackend.service.PictureService;
import com.yupi.picturebackend.service.SpaceService;
import com.yupi.picturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * WebSocket 拦截器,建立前要校验
 */
@Component
@Slf4j
public class WsHandshakeInterceptor implements HandshakeInterceptor {

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    /**
     * 建立前校验
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes 给WebSocketSession 传递数据
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(org.springframework.http.server.ServerHttpRequest request, org.springframework.http.server.ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 对请求进行校验
        if (request instanceof ServletServerHttpRequest){
            HttpServletRequest httpServletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            // 从请求中获取图片id
            String pictureId = httpServletRequest.getParameter("pictureId");
            if (StrUtil.isBlank(pictureId)){
                log.error("缺少图片参数，拒绝握手");
                return false;
            }
            // 获取当前登录用户
            User loginUser = userService.getLoginUser(httpServletRequest);
            if (loginUser == null){
                log.error("用户未登录，拒绝握手");
                return false;
            }
            // 获取图片信息
            Picture picture = pictureService.getById(pictureId);
            if (picture == null){
                log.error("图片不存在，拒绝握手");
                return false;
            }
            // 根据图片的空间id不为空，判断是否为公共
            Long spaceId = picture.getSpaceId();
            if (spaceId == null){
                log.error("该图片位于公共空间，无法建立连接");
                return false;
            }
            // 获取空间信息
            Space space = spaceService.getById(spaceId);
            if (space == null){
                log.error("空间不存在，拒绝握手");
                return false;
            }
            // 判断空间是否为团队空间
            if (space.getSpaceType() != SpaceTypeEnum.TEAM.getValue()){
                log.error("该图片不位于团队空间，无法建立连接");
                return false;
            }
            // 校验该用户是否有编辑图片的权限
            List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
            if (!permissionList.contains(SpaceUserPermissionConstant.PICTURE_EDIT)){
                log.error("用户无权限，拒绝握手");
                return false;
            }
            // 将用户的信息存到 WebSocket 会话中
            attributes.put("user",loginUser);
            attributes.put("userId",loginUser.getId());
            attributes.put("pictureId",Long.valueOf(pictureId));// 避免类型转换异常
        }
        return true;
    }

    @Override
    public void afterHandshake(org.springframework.http.server.ServerHttpRequest request, org.springframework.http.server.ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
